<template>
  <div>
    <el-radio-group v-model="code">
      <!-- 组件 -->
      <el-row
        :gutter="22"
        class="row-choose-box"
        v-for="(item,index) in optionList"
        :key="index">
        <el-col :span="3">
          <el-radio :label="item.code">
            {{item.code}}：
          </el-radio>
        </el-col>
        <el-col :span="15">
          <el-input v-model="item.title"></el-input>
        </el-col>
        <el-col :span="6">
          <el-upload
            class="avatar-uploader"
            action="/"
            :show-file-list="false"
            :on-change="res=>imgPreview(res, item)">
            <img v-if="item.img" :src="item.img" class="avatar">
            <i v-else class="avatar-uploader-icon">点击上传</i>
          </el-upload>
        </el-col>
      </el-row>
      <!-- 组件   END -->
    </el-radio-group>
  </div>
</template>

<script>
export default {
  name: 'RadioBox',
  props: {
    options: {
      required: true
    }
  },
  data () {
    return {
      code: 'A'
    }
  },
  created: function () {
    // 初始化选中项
    const arr = this.optionList.filter(item => {
      return item.isRight === 1
    })
    // 单选只取第一项，其余项逻辑问题报错
    this.code = arr.length === 1 ? arr[0] : new Error('this options should be only one option!')
    // 单选只取第一项
    // this.code = arr[0]
  },
  methods: {
    // 照片上传
    imgPreview: function(file, item) {
      const fileName = file.name;
      const regex = /(.jpg|.jpeg|.gif|.png|.bmp)$/;
      if (regex.test(fileName.toLowerCase())) {
        item.img = URL.createObjectURL(file.raw) // 获取URL
      } else {
        this.$message.error('请选择图片文件');
      }
    },
    onChange () {
      if (!this.options) {
        this.$emit('changed', this.optionList)
      }
    }
  },
  watch: {
    code () {
      const index = this.optionList.findIndex(item => {
        return item.code === this.code
      })
      for (let i = 0; i < this.optionList.length; i++) {
        this.optionList[i].isRight = index === i
      }
    },
    optionList: {
      handler () {
        this.onChange()
      },
      deep: true
    }
  },
  computed: {
    optionList () {
      // 去掉后面多余项只保留四项
      return Array.isArray(this.options) && this.options ? this.options.slice(0, 4) : [
        {
          code: 'A',
          title: '',
          img: '',
          isRight: true
        },
        {
          code: 'B',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'C',
          title: '',
          img: '',
          isRight: false
        },
        {
          code: 'D',
          title: '',
          img: '',
          isRight: false
        }
      ]
    }
  }
}
</script>

<style scoped>
.row-choose-box {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}
</style>
